// 导入uni-id-common模块和数据库
// 使用相对路径引用uni_modules中的模块
const uniID = require('../../../uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/index.js');
const db = uniCloud.database();
// 导入配置中心
const createConfigCenter = require('../../../uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js');

/**
 * 获取帖子详情
 * @param {Object} event 客户端传入的参数
 * @param {String} event.token 用户token
 * @param {String} event.postId 动态ID
 * @param {Object} context 上下文信息
 */
exports.main = async (event, context) => {
  const { token, postId } = event;
  
  // 初始化配置中心并获取uni-id配置
  const config = createConfigCenter({ pluginId: 'uni-id' });
  const uniIdConfig = config.config();
  
  // 初始化uniID实例
  const uniIDIns = uniID.createInstance({
    context,
    config: uniIdConfig
  });
  
  // 校验参数
  if (!postId) {
    return {
      code: 1,
      message: '动态ID不能为空'
    };
  }
  
  // 检查并验证token
  let currentUserId = null;
  if (token) {
    try {
      const checkTokenRes = await uniIDIns.checkToken(token);
      if (!checkTokenRes.code) {
        currentUserId = checkTokenRes.uid;
      }
    } catch (error) {
      console.error('token验证失败:', error);
    }
  }
  
  try {
    // 查询帖子详情
    const dynamicCollection = db.collection('dynamic_posts');
    const postRes = await dynamicCollection.doc(postId).get();
    
    if (!postRes.data) {
      return {
        code: 1,
        message: '动态不存在'
      };
    }
    
    let post = postRes.data;
    
    // 检查权限
    if (post.privacy === 'private' && post.userId !== currentUserId) {
      // 检查是否是关注者
      if (currentUserId) {
        const followRes = await db.collection('user_follows')
          .where({
            userId: currentUserId,
            followId: post.userId
          })
          .count();
        
        if (followRes.total === 0) {
          return {
            code: 1,
            message: '无权限查看此动态'
          };
        }
      } else {
        return {
          code: 1,
          message: '请先登录'
        };
      }
    } else if (post.privacy === 'followers' && post.userId !== currentUserId) {
      // 检查是否是关注者
      if (currentUserId) {
        const followRes = await db.collection('user_follows')
          .where({
            userId: currentUserId,
            followId: post.userId
          })
          .count();
        
        if (followRes.total === 0) {
          return {
            code: 1,
            message: '无权限查看此动态'
          };
        }
      } else {
        return {
          code: 1,
          message: '请先登录'
        };
      }
    }
    
    // 如果用户已登录，检查用户是否点赞了此动态
    if (currentUserId) {
      const likeRes = await db.collection('post_likes')
        .where({
          userId: currentUserId,
          postId: postId
        })
        .count();
      
      post.isLiked = likeRes.total > 0;
    } else {
      post.isLiked = false;
    }
    
    return {
      code: 0,
      message: '获取动态详情成功',
      data: post
    };
  } catch (error) {
    console.error('获取动态详情失败:', error);
    return {
      code: 1,
      message: '获取动态详情失败',
      data: error.message
    };
  }
};